package com.jjvu.news.util;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;



public class VScode {
	private int w=120,h=32;
	private Color bgColor=new Color(240, 240, 240);
	private Random random=new Random();
	//private StringBuilder code=new StringBuilder(4);//记录随机验证码
	private String code="";
//	创建图片
	private BufferedImage creatImage() {
//		创建图片
//		设置背景图片
		BufferedImage img=new BufferedImage(w, h, BufferedImage.TYPE_INT_BGR);
//		设置画笔颜色
		img.getGraphics().setColor(bgColor);
//		填充一个与图片大小一样的矩形
		img.getGraphics().fillRect(0, 0, w, h);
		return img;
	}
//	随机生成颜色
	private Color randomColor() {
		int r=random.nextInt(256);
		int g=random.nextInt(256);
		int b=random.nextInt(256);
		return new Color(r,g,b);
	}
//	随机生成字体
	private String[] fontName= {"宋体","华文楷体","黑体","华文新魏","华文隶书","微软雅黑","楷体_GB2312"};
	private int[] fontSize= {26,27,28,29,30,31};
	private Font randomFont() {
		int index=random.nextInt(fontName.length);
		String name=fontName[index];
		int style=random.nextInt(4);
		
		index=random.nextInt(fontSize.length);
		int size=fontSize[index];
		return new Font(name,style,size);
	}
//	随机生成字符
	private String codes="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
	private String randomChar() {
		int index=random.nextInt(codes.length());
		return codes.charAt(index)+"";
	}
	
//	随机生成干扰线
	private void drawLine(BufferedImage img) {
		Graphics2D g=(Graphics2D)img.getGraphics();
		g.setColor(Color.black);
		g.setStroke(new BasicStroke(1.2f));//设置字体粗细
		for(int i=0;i<2;i++) {
			int x1=random.nextInt(w);
			int y1=random.nextInt(h);
			int x2=random.nextInt(w);
			int y2=random.nextInt(h);
			g.drawLine(x1, y1, x2, y2);
		}
	}
//	获取图片
	public BufferedImage getImage(HttpServletRequest request,HttpServletResponse response) {
		HttpSession session = request.getSession();
//		写字符：范围，字体，字号，粗体，颜色--随机生成
		
		BufferedImage img=creatImage();
		Graphics g=img.getGraphics();
//		画东西
		for(int i=0;i<4;i++) {
			String ch=this.randomChar();//随机生成字符
			//code.append(ch);
			code+=ch;
			g.setColor(this.randomColor());//随机颜色
			g.setFont(this.randomFont());//随机字体
			g.drawString(ch, w/4*i, h-5);
		}
		session.setAttribute("yzm", code);
		this.drawLine(img);//添加干扰线
		return img;
	}
//	记录验证码
	public String getCode() {
		return code.toString();
	}
//	保存图片
	public static void saveImage(BufferedImage img,OutputStream out) throws Exception {
		ImageIO.write(img, "JPEG", out);
	}
}
